my $file = $ARGV[0];
open input, "<$file" or die "cannot open $file";
#my  $save = "extract_c5.dat";
#open SAVE_FILE, ">$save" or die "cannot open $save";
print "start ===========\n";

@max_seq=();
$MIN_NODE = 1000;
$MAX_NODE = 1300;
$SINK_NODE = 60001;
#for($i=1000; $i<1300; $i++)
#{
#	$logFile = "./logData/$i.log";
#	$port = "SAVE_LOG_$i";
#	open $port, ">$logFile" or die "cannot open $logFile";
#	$max_seq[$i]=0;
#}
$logCount=0;
$retransmitCount=0;
my $line = "";
%name2file = ();
$noError = 0;
$noCorrect = 0;
while($line = <input>)
{
	chomp;
	@rs = split(' ', $line);
	$type = hex("$rs[19]");
	if(0xC5 == $type)
	{
		$size = hex("$rs[20]");
		$source = hex("$rs[21]$rs[22]");
		#$port = "SAVE_LOG_$source";		
		#print $port "$source ";	
		
		for($i=0; $i<$size; $i++)
		{
			$logCount++;
			
			#$port = "SAVE_LOG_$source";
			$temp=23+$i*15;
			$relatedNode = hex("$rs[$temp+1]$rs[$temp+2]");
			$logSeq = hex("$rs[$temp+13]$rs[$temp+14]");
			$controlType = hex("$rs[$temp]");
			if($controlType == 0xFA)
			{
				$retransmitCount++;
			}
			#if(0xAA==$controlType || 0xFA==$controlType || 0xFB==$controlType || 0xFF==$controlType || 0xBB==$controlType || 0xCC==$controlType || 0xDD==$controlType || 0xFD==$controlType || 0xAD==$controlType || 0xAE==$controlType || 0xFE==$controlType)
			#{
				if($logSeq > $max_seq[$source])
				{
					$max_seq[$source] = $logSeq;
				}
				if ($relatedNode != $SINK_NODE && ($relatedNode > $MAX_NODE || $relatedNode < $MIN_NODE)){
					print "$relatedNode\t$logSeq\t@rs[$temp..$temp+14]\n";
					#print $line, "\n";
					++$noError;
					next;
				}
				#$port = "SAVE_LOG_$relatedNode";
				if (exists $name2file{$relatedNode})
				{
				}else{
					$filename = "./C5log/$relatedNode.log";
					$port = "SAVE_LOG_$relatedNode";
					print "======open file $filename\n";
					open $port,  ">$filename" or die "cannot open $filename\n";
					$name2file{$relatedNode} = $port;
				}
				#print $OUTPUT;
				$port = $name2file{$relatedNode};
				print $port "$source 00 00 00 00 00 00 00 00 ";
				@byte = @rs[$temp..$temp+14]; 
				print $port "@byte ";
				++$noCorrect;
#				for($index=$temp; $index<$temp+15; $index++)
#				{	
#					$byte = $rs[$index];
#
#				}
				print $port "\n";
				#$i+=15;
			#}
		}
	}

}

foreach $key (keys %name2file){
	close $name2file[$key];
}




#for($i=1000; $i<1300; $i++)
#{	
#	$port = "SAVE_LOG_$i";
#	close $port;
#}

#$k=$retransmitCount/$logCount;
$ratio = $noCorrect/($noCorrect + $noError);
print "number of error: $noError $noCorrect $ratio \n";